package com.movies.bean;

import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.stereotype.Service;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by chemeng on 2017/3/23.
 */
@Service
public class AuthenticationHandler implements AuthenticationSuccessHandler {
    private static final HttpSessionRequestCache requestCache;

    static {
        requestCache = new HttpSessionRequestCache();
    }

    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        HttpServletRequest wrappedSavedRequest = requestCache.getMatchingRequest(
                httpServletRequest, httpServletResponse);
        System.out.println(httpServletRequest.getRequestURI());
        System.out.println(httpServletRequest.getServerName());
        System.out.println(httpServletRequest.getServerPort());
        String //hello = httpServletRequest.getScheme() + "://" + httpServletRequest.getServerName() + ":" + httpServletRequest.getServerPort() + "/hello.html";
                hello = "http://localhost:8080/hello.html";
        Cookie cookie = new Cookie("JSESSIONID", httpServletRequest.getSession().getId());
        httpServletResponse.addCookie(cookie);

        if (null != wrappedSavedRequest) {
            httpServletRequest = wrappedSavedRequest;
        }
        //httpServletResponse.sendRedirect(hello);
    }
}
